package day16;
//本类用于改造多线程售票案例。解决数据安全的问题
public class TestRunnableV2 {
    public static void main(String[] args) {
        //创建目标业务类对象
        TicketR2 target = new TicketR2();

        //创建4个线程对象
        Thread t1 = new Thread(target);
        Thread t2 = new Thread(target);
        Thread t3 = new Thread(target);
        Thread t4 = new Thread(target);

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}



//1创建自定义的多线程售票类
class TicketR2 implements Runnable {
    int tickets = 100;
    Object o = new  Object();   //创建所对象
    @Override    ///定义成员变量，保存票数
    public void run() {
        while(true){             //4完成业务：循环售票
            synchronized (o){
                if(tickets > 0){
                    try {
                        Thread.sleep(10);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"="+tickets--);
                }
                if(tickets == 0) break;
            }               //5设置同步快，这里的锁一定要求是唯一的
        }

    }

}